#include "dynamiclayout.h"

#include <QStyle>      // 支持样式操作
#include <QVariant>    // 支持属性类型封装
#include <QDebug>

#include <cmath>

DynamicLayout::DynamicLayout(QWidget* parent)
    : QGridLayout(parent), m_selectedWidget(nullptr)
{
    // 初始化策略对象
    m_strategies[LayoutMode::One] = new OneGridStrategy();
    m_strategies[LayoutMode::Linear] = new LinearStrategy();
    m_strategies[LayoutMode::Grid] = new GridStrategy();
    m_strategies[LayoutMode::AutoGrid] = new AutoGridStrategy(); // 注册新策略
}

DynamicLayout::~DynamicLayout() {
    qDeleteAll(m_strategies); // 清理策略对象
}

void DynamicLayout::addManagedWidget(QWidget* widget) {

    if(!widget) {
        qDebug() << "addManagedWidget<错误>：空指针";
        return;
    }

//    widget->installEventFilter(this);  // 安装事件过滤器
    if(m_widgets.size() >= MAX_WIDGET) {
        qDebug() << "DynamicLayout：窗口数量已达上限";
//        widget->deleteLater(); ///bug:删除会导致程序崩溃
        return;
    }

    widget->setAttribute(Qt::WA_StyledBackground); // 启用样式背景
    m_widgets.append(widget);          // 加入托管集合

    updateLayout();                    // 触发布局更新
}

void DynamicLayout::removeManagedWidget(QWidget* widget) {

    if(!widget) {
        qDebug() << "removeManagedWidget<错误>：空指针";
        return;
    }

    if(m_widgets.isEmpty()) {
        qDebug() << "布局没有窗口可以删除了";
        return;
    }

    // 新增样式重置
    widget->setStyleSheet(""); // 清空直接样式
    widget->setProperty("selected", QVariant(false)); // 重置动态属性
    widget->removeEventFilter(this);   // 移除事件监听
    m_widgets.removeAll(widget);       // 从集合中删除
    QGridLayout::removeWidget(widget); // 从布局移除
    widget->hide();// 隐藏避免重影
//    widget->deleteLater();
    updateLayout();                    // 触发布局更新
}

QPoint DynamicLayout::getWidgetPosition(QWidget* widget) const {
    if (!widget || !m_widgets.contains(widget)) { // 假设 m_widgets 是存储控件的容器
        qWarning() << "Invalid widget or widget not in layout";
        return QPoint(-1, -1);
    }
    int index = m_widgets.indexOf(widget);
    if(index == -1) return QPoint(-1, -1);

    // 关键修改：传递 index 和 totalCount
    int totalCount = m_widgets.size(); // 获取总控件数
    return currentStrategy()->getWidgetPosition(index, totalCount);
}

QWidget* DynamicLayout::selectedWidget() const {
    return m_selectedWidget;
}

// dynamiclayout.cpp 修改事件过滤器
bool DynamicLayout::eventFilter(QObject* watched, QEvent* event)
{
    if (!event) return QGridLayout::eventFilter(watched, event); // 空指针防御

    if (event->type() == QEvent::MouseButtonPress)
    {
        qDebug() << "";qDebug() << "";
        qDebug() << "鼠标按下事件来了 " << watched;
        if (QWidget* clickedWidget = qobject_cast<QWidget*>(watched))
        {
            qDebug() << "QWidget* clickedWidget： " << clickedWidget;
            qDebug() << "QWidget* clickedWidget->parent()： " << clickedWidget->parent();
            qDebug() << "qobject_cast<QWidget*>(watched)： " << qobject_cast<QWidget*>(watched);
            qDebug() << "m_selectedWidget： " << m_selectedWidget;
            QWidget *clickedWIdgetParent = qobject_cast<QWidget*>(clickedWidget->parent());
#if 1
            if (clickedWIdgetParent == m_selectedWidget) return true; // 重复点击优化

            qDebug() << "不是重复点击";
            qDebug() << "";qDebug() << "";

            // 清除旧控件样式
            if (m_selectedWidget) {
                m_selectedWidget->setStyleSheet("");
            }

            // 设置新选中样式
            clickedWIdgetParent->setStyleSheet("QWidget { border: 2px solid red; }");

            m_selectedWidget = clickedWIdgetParent;
            emit selectionChanged(clickedWIdgetParent);
            return true; // 事件已处理

#endif
        }
    }
    return QGridLayout::eventFilter(watched, event);
}

void DynamicLayout::updateLayout() {

//    qDebug() << "updateLayout 调用了";
//    qDebug() << "m_widgets_count:" << m_widgets.size();
//    qDebug() << "m_widgets:" << m_widgets;
    LayoutMode newMode = calculateLayoutMode();
    if(m_OneLayoutFlag) {
        newMode = LayoutMode::One;
    }

//    qDebug() << "newMode:" << newMode;
    if(newMode != m_currentMode) {
        m_currentMode = newMode;// 更新模式

    }
    reorganizeLayout();// 更新布局
}

DynamicLayout::LayoutMode DynamicLayout::calculateLayoutMode() const {
//    qDebug() << "calculateLayoutMode 调用了";
    return m_widgets.size() > 3 ? Grid : Linear;
}

// 高效清空布局（不删除控件）
void DynamicLayout::clearLayout(QLayout* layout, bool deleteWidgets) {
    while (QLayoutItem* item = layout->takeAt(0)) {
        if (QWidget* widget = item->widget()) {
            if (deleteWidgets) {
                widget->deleteLater();// 安全删除
            } else {
                widget->setParent(nullptr);// 解除父子关系
            }
        }
        delete item; // 必须删除布局项
    }
    // 强制布局重计算
    if(QWidget* pw = parentWidget()) {
        pw->updateGeometry();
    }
}

void DynamicLayout::reorganizeLayout() {
    clearLayout(this, false);// 清除旧布局但保留控件

    qDebug() << "当前Model:" << m_currentMode;

    // 应用新策略
    currentStrategy()->arrangeWidgets(this, m_widgets);

    this->update();
}

LayoutStrategy* DynamicLayout::currentStrategy() const {
    return m_strategies[m_currentMode];
}

bool DynamicLayout::getOneLayoutFlag() const
{
    return m_OneLayoutFlag;
}

QWidget *DynamicLayout::getSelectedWidget() const
{
    return m_selectedWidget;
}

void DynamicLayout::do_selectedWidget(QWidget *seleWidget)
{
    m_selectedWidget = seleWidget;
}

void DynamicLayout::setOneLayoutFlag(bool OneLayoutFlag)
{
    m_OneLayoutFlag = OneLayoutFlag;

    updateLayout();
}


/** LinearStrategy */

void LinearStrategy::arrangeWidgets(QGridLayout* layout, const QList<QWidget*>& widgets) {
    for(int i = 0; i < widgets.size(); ++i) {
        layout->addWidget(widgets[i], i, 0); // 全部控件放在第0列，第n行
    }
}

QPoint LinearStrategy::getWidgetPosition(int index, int totalCount) const {
    Q_UNUSED(totalCount)
    return QPoint(index, 0); // 线性布局坐标映射规则
}




/** GridStrategy */

void GridStrategy::arrangeWidgets(QGridLayout* layout, const QList<QWidget*>& widgets) {
    for(int i = 0; i < widgets.size(); ++i) {
        int row = i / 2;  // 计算行号：每2个控件换行
        int col = i % 2;  // 计算列号：0/1交替
        layout->addWidget(widgets[i], row, col);
    }
}

QPoint GridStrategy::getWidgetPosition(int index, int totalCount) const {
    Q_UNUSED(totalCount)
    return QPoint(index / 2, index % 2); // 网格布局坐标映射
}



/** AutoGridStrategy */

QPoint AutoGridStrategy::getWidgetPosition(int index, int totalCount) const
{
    if (totalCount <= 0 || index < 0 || index >= totalCount) {
        return QPoint(-1, -1);  // 无效参数保护
    }

    const double sqrtSize = sqrt(totalCount);
    int colLen = static_cast<int>(floor(sqrtSize));

    if (colLen == sqrtSize && colLen > 1) {
        colLen--;
    }

    const int columns = colLen + 1;
    return QPoint(index / columns, index % columns);
}


void AutoGridStrategy::arrangeWidgets(QGridLayout *layout, const QList<QWidget *> &widgets)
{
    if (widgets.isEmpty()) return;

    const int itemCount = widgets.size();
    const double sqrtSize = sqrt(itemCount);
    int colLen = static_cast<int>(floor(sqrtSize));

    // 完美平方数优化：当控件数刚好是平方数时，减少一行提升布局紧凑性
    // 示例：4个控件时（2x2）保持原样，但9个控件时改为3x3 -> 3x3（此处可能需要验证原逻辑是否正确）
    if (colLen == sqrtSize && colLen > 1) {
        colLen--;
    }

    // 计算实际列数（+1补偿floor操作）
    const int columns = colLen + 1;

    // 网格化排列控件
    for (int i = 0; i < itemCount; ++i) {
        const int row = i / columns;  // 计算行号
        const int col = i % columns;  // 计算列号
        layout->addWidget(widgets[i], row, col);
    }
}


/** OneGridStrategy */

void OneGridStrategy::arrangeWidgets(QGridLayout *layout, const QList<QWidget *> &widgets)
{
    Q_UNUSED(layout);
    Q_UNUSED(widgets);

    if(DynamicLayout *dyLayout = qobject_cast<DynamicLayout *>(layout))
    {
        if(widgets.isEmpty()) return;

//        dyLayout->clearLayout(dyLayout, false);

        QWidget *widget = dyLayout->getSelectedWidget();

        qDebug() << "SelectedWidget:" << widget;

        if(widget) {
            dyLayout->addWidget(widget, 0, 0);

            qDebug() << "布局单独填加一个窗口";
        } else {
            qDebug() << "空指针:" << widget;
            dyLayout->setOneLayoutFlag(false);
        }
    }
}

QPoint OneGridStrategy::getWidgetPosition(int index, int totalCount) const
{
    Q_UNUSED(index);
    Q_UNUSED(totalCount);
    return QPoint(0,0);
}
